package com.coocaa.coolink_tvos_mobile_demo;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.coocaa.coolink_tvos_mobile_demo.databinding.ActivityMainBinding;
import com.coocaa.coolink_tvos_mobile_demo.events.MessageEvent;
import com.coocaa.coolink_tvos_mobile_demo.model.Key;
import com.coocaa.coolink_tvos_mobile_demo.model.KeyBoard;
import com.coocaa.coolink_tvos_mobile_demo.ui.dashboard.DashboardFragment;
import com.coocaa.coolink_tvos_mobile_demo.ui.home.HomeFragment;
import com.coocaa.coolink_tvos_mobile_demo.utils.UniqueDeviceID;
import com.coocaa.obrr_sdk.easyapi.ObrrSDKEasyApi;
import com.coocaa.obrr_sdk.easyapi.models.EasyHttpInitOpt;
import com.coocaa.obrr_sdk.easyapi.models.EasyInitOpt;
import com.coocaa.obrr_sdk.easyapi.models.UniqueTunnel;
import com.coocaa.obrr_sdk.easyinterface.IObrrSDKEasy;
import com.coocaa.obrr_sdk.models.FileDownloadFinish;
import com.coocaa.obrr_sdk.models.FileDownloadProgress;
import com.coocaa.obrr_sdk.models.FileDownloadStart;
import com.coocaa.obrr_sdk.models.LogConfig;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

public class MainActivity extends AppCompatActivity implements DashboardFragment.SendKeyBoardListener, HomeFragment.IRemoteItemSelected {

    private ActivityMainBinding binding;

    CustomServerConnectorListener serverConnectorListener;
    CustomFileListener fileListener;

    AtomicBoolean isEasyApiServiceStarted = new AtomicBoolean(false);
    AtomicReference<String> globalClientID = new AtomicReference<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(binding.navView, navController);

        if (!isEasyApiServiceStarted.get()) {
            initCoolinkEasyApi();
        }

    }

    public void initCoolinkEasyApi(){
        serverConnectorListener = new CustomServerConnectorListener();
        fileListener = new CustomFileListener();

        String deviceID = "tvos.did-" +UniqueDeviceID.getDeviceId(this);
        EasyInitOpt iniOpt = new EasyInitOpt(
                "http://obrr-api-test.skyworthiot.com",
                "12345678901234567890123456789012",
                "d2969e51fe8ba0d4415270e8eb27ed62",
                "com.localhost.test",
                deviceID, // 需要设置为特定ID
                "tvos.uid-coolink");// 此处的userID与开发板上demo程序的uid可以保持一致，可以通过userID来获取所有的设备列表

        EasyHttpInitOpt httpInitOpt = new EasyHttpInitOpt(
                "static",
                MainActivity.this.getCacheDir().getAbsolutePath(),
                "remote",
                "remote_map"
        );
        // 顺序不要变
        ObrrSDKEasyApi.getInstance().setServerConnectorListener(serverConnectorListener);
        ObrrSDKEasyApi.getInstance().initEasySDK(
                MainActivity.this,
                LogConfig.DEBUG,
                iniOpt,
                httpInitOpt,
                MainActivity.this.getCacheDir().getAbsolutePath(),
                fileListener,
                true
        );
        EventBus.getDefault().post(new MessageEvent(1,""));
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public String sendKeyBoard(IObrrSDKEasy.ISendContentResult resultListener, Key key) {
        String sourceClientID = globalClientID.get();
        String remoteClientID = globalRemoteClientID.get();
        if ( !TextUtils.isEmpty(sourceClientID) && !TextUtils.isEmpty(remoteClientID)){
            if (ObrrSDKEasyApi.getInstance().isDeviceConnectReady(remoteClientID)){
                //判断存在连接，并且与对端设备处于连接状态
                return ObrrSDKEasyApi.getInstance().sendContent(resultListener,remoteClientID,"KEYPAD", KeyBoard.convert(key));
            }
        }
        return null;
    }

    AtomicReference<String> globalRemoteClientID = new AtomicReference<>("");

    @Override
    public void setCurrentRemoteID(String remoteID) {
        globalRemoteClientID.set(remoteID);
    }

    class CustomServerConnectorListener implements IObrrSDKEasy.IServerConnectorListener{
        @Override
        public void onTunnelServiceReady(String clientID) {
            isEasyApiServiceStarted.set(true);
            globalClientID.set(clientID);
            //833001ece3aa2d9cb7141f45fce4f90d
            Log.i(getClass().getSimpleName(),"onTunnelServiceReady: = " + clientID);
        }

        @Override
        public void onConnectFailed(UniqueTunnel uniqueTunnel, String s) {

        }

        @Override
        public void onConnected(UniqueTunnel uniqueTunnel, boolean b) {
        }

        @Override
        public void onReadyToSend(UniqueTunnel uniqueTunnel, boolean b) {
            Log.d(getClass().getSimpleName(),"ReadyToSend!");
            // can send ...
            EventBus.getDefault().post(new MessageEvent(3,uniqueTunnel.getRemoteID()));
        }

        @Override
        public void onConnectLinkChanged(UniqueTunnel uniqueTunnel, boolean b) {

        }

        @Override
        public void onConnectUnStable(UniqueTunnel uniqueTunnel, boolean b) {

        }

        @Override
        public void onPreDisconnect(UniqueTunnel uniqueTunnel, boolean b) {
        }

        @Override
        public void onDisconnected(UniqueTunnel uniqueTunnel, boolean b, String s) {

        }

        @Override
        public void onContentReceived(UniqueTunnel uniqueTunnel, boolean b, String s, String s1, String s2) {

        }

        @Override
        public void onSameRemoteIDConnectKickOff(UniqueTunnel uniqueTunnel) {

        }
    }

    // latency implementation
    class CustomFileListener extends IObrrSDKEasy.IFileTransferServerListener implements IObrrSDKEasy.IFileTransferListener {
        // not used!
        @Override
        public boolean isServerListener() {
            return true;
        }

        @Override
        public void onReceivedStart(UniqueTunnel uniqueTunnel, String s, String s1, FileDownloadStart fileDownloadStart) {

        }

        @Override
        public void onReceivedInterruptedErr(UniqueTunnel uniqueTunnel, String s, String s1, String s2) {

        }

        @Override
        public void onReceivedProgress(UniqueTunnel uniqueTunnel, String s, String s1, FileDownloadProgress fileDownloadProgress) {

        }

        @Override
        public void onReceivedFinish(UniqueTunnel uniqueTunnel, String s, String s1, FileDownloadFinish fileDownloadFinish) {

        }
    }
}